﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Configuration;

namespace Gasco.DataAccess
{
    public static class DatabaseHelper
    {

        public static GascoDBDataContext GetData()
        {
            var db = new GascoDBDataContext();
            return db;
        }

        public static T Insert<T>(T obj) where T : LINQEntityBase
        { 
          using(var db=GetData())
          {
              db.GetTable<T>().InsertOnSubmit(obj);
              db.SubmitChanges();
              db.Refresh(RefreshMode.OverwriteCurrentValues, obj);
              return obj;
          }
        }

        public static void Update<T>(T obj) where T : LINQEntityBase
        {
            using (var db=GetData())
            {
                db.DeferredLoadingEnabled = false;
                obj.SynchroniseWithDataContext(db, true);
                db.SubmitChanges();
            }
        }

        public static void Delete<T>(T obj) where T : LINQEntityBase
        {
            using (var db = GetData())
            {
                Table<T> table = db.GetTable<T>();
                db.DeferredLoadingEnabled = false;
                obj.SetAsDeleteOnSubmit(true);
                obj.SynchroniseWithDataContext(db, true);
                db.SubmitChanges();
            }
        }

    }
}
